package com.paradogs.login.controller;

import com.paradogs.common.utils.JwtUtils;
import com.paradogs.common.utils.R;
import com.paradogs.common.utils.Wrap;
import com.paradogs.login.dao.AccountDao;
import com.paradogs.login.pojo.dto.LoginDTO;
import com.paradogs.login.pojo.dto.ModifyPwdDTO;
import com.paradogs.login.pojo.dto.RegisterDTO;
import com.paradogs.login.pojo.entity.Account;
import com.paradogs.login.pojo.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author: yumi
 * @date: 2024/10/9  17:25
 * @Description: TODO
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountDao accountDao;

    /** 账号登录 */
    @PostMapping("/login")
    public R<LoginVO> login(@Validated @RequestBody LoginDTO dto) {

        Account account = accountDao.selectOne(Wrap.<Account>lbq().eq(Account::getAccount, dto.getAccount()));
        if (account == null) {
            return R.fail("账号不存在");
        }
        if (!account.getPassword().equals(dto.getPassword())) {
            return R.fail("密码错误");
        }
        if (account.getStatus().equals("OFF")) {
            return R.fail("账号已封禁");
        }

        return R.success(new LoginVO(JwtUtils.buildToken(account.getUid(), account.getIsGM())));
    }

    /** 账号注册 */
    @PostMapping("/register")
    public R<?> register(@Validated @RequestBody RegisterDTO dto) {
        if (!dto.getPassword().equals(dto.getPassword2())) {
            return R.fail("两次密码不正确");
        }
        boolean exists = accountDao.exists(Wrap.<Account>lbq().eq(Account::getAccount, dto.getAccount()));
        if (exists) {
            return R.fail("账号已存在");
        }
        try {
            accountDao.insert(new Account(dto.getAccount(), dto.getPassword()));
        } catch (Exception e) {
            log.error("{}", e.getMessage(), e);
            return R.fail("注册失败，请重新尝试");
        }

        return R.success();
    }

    /** 修改密码 */
    @PostMapping("/modifyPwd")
    public R<?> modifyPwd(@Validated @RequestBody ModifyPwdDTO dto) {

        Account account = accountDao.selectOne(Wrap.<Account>lbq().eq(Account::getAccount, dto.getAccount()));
        if (account == null) {
            return R.fail("账号不存在");
        }
        if (!dto.getPassword().equals(dto.getPassword2())) {
            return R.fail("两次密码不正确");
        }
        account.setPassword(dto.getPassword());
        accountDao.updateById(account);

        return R.success();
    }

}
